<template>
  <a-modal
    v-model:open="open"
    title="历史路径执行情况"
    :width="1200"
    :footer="null"
    :mask-closable="false"
  >
    <a-spin :spinning="loading">
      <div style="display: flex; justify-content: space-between">
        <div
          style="
            width: 240px;
            height: 650px;
            padding-top: 10px;
            padding-right: 5px;
            overflow: hidden auto;
          "
        >
          <template v-if="routePath.length > 0">
            <a-timeline>
              <template v-for="(item, index) in routePath">
                <a-timeline-item v-if="item.executionState == '生成中'" :key="index">
                  <div
                    :class="routePathIndex == index ? 'route-item route-item-active' : 'route-item'"
                    @click="routePathHandle(item, index)"
                  >
                    <div style="display: flex; justify-content: space-between">
                      <span class="route-name route-manage-name">{{ item.pathName }}</span>
                      <span class="route-path-state mana-span">生成中</span>
                    </div>
                    <div class="route-time route-manage-time">--~--</div>
                  </div>
                </a-timeline-item>
                <a-timeline-item v-if="item.executionState == '管理中'" :key="index">
                  <div
                    :class="routePathIndex == index ? 'route-item route-item-active' : 'route-item'"
                    @click="routePathHandle(item, index)"
                  >
                    <div style="display: flex; justify-content: space-between">
                      <span class="route-name route-manage-name">{{ item.pathName }}</span>
                      <span class="route-path-state mana-span">管理中</span>
                    </div>
                    <div class="route-time route-manage-time">
                      {{ dayjs(item.startTime).format('YYYY-MM-DD') }}~{{
                        dayjs(item.endTime).format('YYYY-MM-DD')
                      }}
                    </div>
                  </div>
                </a-timeline-item>
                <a-timeline-item color="gray" v-if="item.executionState == '已结束'" :key="index">
                  <div
                    :class="routePathIndex == index ? 'route-item route-item-active' : 'route-item'"
                    @click="routePathHandle(item, index)"
                  >
                    <div style="display: flex; justify-content: space-between">
                      <span class="route-name">{{ item.pathName }}</span>
                      <span class="route-path-state over-span">已结束</span>
                    </div>
                    <div class="route-time">
                      {{ dayjs(item.startTime).format('YYYY-MM-DD') }}~{{
                        dayjs(item.endTime).format('YYYY-MM-DD')
                      }}
                    </div>
                  </div>
                </a-timeline-item>
                <a-timeline-item color="gray" v-if="item.executionState == '已终止'" :key="index">
                  <div
                    :class="routePathIndex == index ? 'route-item route-item-active' : 'route-item'"
                    @click="routePathHandle(item, index)"
                  >
                    <div style="display: flex; justify-content: space-between">
                      <span class="route-name">{{ item.pathName }}</span>
                      <span class="route-path-state close-span">已终止</span>
                    </div>
                    <div class="route-time">
                      {{ dayjs(item.startTime).format('YYYY-MM-DD') }}~{{
                        dayjs(item.endTime).format('YYYY-MM-DD')
                      }}
                    </div>
                  </div>
                </a-timeline-item>
              </template>
            </a-timeline>
          </template>
          <template v-else>
            <a-empty :image="simpleImage" />
          </template>
        </div>
        <div style="width: 910px" :key="routePathIndex">
          <a-tabs v-model:activeKey="tempTabsIndex" @change="changeTab" type="card">
            <a-tab-pane v-for="(item, index) in templateTypeList" :key="index" :tab="item" />
          </a-tabs>
          <Condition
            :condition="condition"
            :btns="['search', 'reset']"
            @search="searchHandle"
            @reset="reset"
          />
          <a-table
            size="small"
            :pagination="pagination"
            :columns="columns"
            :data-source="dataSource"
            @change="paginationChange"
            :scroll="{ y: 500 }"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'isRead'">
                <template v-if="!record.pushState"> / </template>
                <template v-else>
                  <a-tag v-if="record.isRead" color="blue"> 已完成 </a-tag>
                  <a-tag
                    v-if="!record.isRead"
                    color="#FFF3E8"
                    style="color: #f77234; border-color: #f77234"
                  >
                    未完成
                  </a-tag>
                </template>
              </template>

              <template v-if="column.key === 'pushState'">
                <a-tag
                  v-if="record.pushState"
                  color="#E8FFEA"
                  style="color: #00b42a; border-color: #00b42a"
                >
                  已推送
                </a-tag>
                <a-tag v-if="!record.pushState" style="border-color: #e5e6eb"> 未推送 </a-tag>
              </template>
              <template v-if="column.dataIndex == 'itemContent'">
                <a-popover
                  title="推送内容"
                  trigger="click"
                  placement="topRight"
                  :overlayStyle="{ width: '300px' }"
                >
                  <template #content>
                    <div style="max-height: 300px; padding: 0 10px; overflow: hidden auto">
                      <pre style="word-wrap: break-word; white-space: pre-wrap">{{
                        record.itemContent
                      }}</pre>
                    </div>
                  </template>
                  <div
                    style="
                      display: -webkit-box;
                      overflow: hidden;
                      text-overflow: ellipsis;
                      -webkit-line-clamp: 3;
                      cursor: pointer;
                      -webkit-box-orient: vertical;
                    "
                  >
                    {{ record.itemContent }}
                  </div>
                </a-popover>
              </template>
              <template v-if="column.key === 'action'">
                <a-button
                  type="link"
                  v-if="record.isSeeBtn && record.isRead"
                  @click="goDetail(record)"
                >
                  {{
                    manaageTypeDict[templateTypeList[tempTabsIndex]]
                      ? manaageTypeDict[templateTypeList[tempTabsIndex]]
                      : '查看详情'
                  }}
                </a-button>
                <!-- v-if="record.isEdit" :disabled="!hasEdit" -->
                <a-button
                  v-if="
                    routePath[routePathIndex] &&
                    routePath[routePathIndex].executionState == '管理中' &&
                    ['健康处方', '健康随访', '就诊提醒'].includes(
                      templateTypeList[tempTabsIndex]
                    ) &&
                    !record.pushState
                  "
                  type="link"
                  @click="editPlan(record)"
                  :disabled="!hasEdit"
                  >修改</a-button
                >
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </a-spin>
  </a-modal>

  <!-- 修改方案 -->
  <a-modal v-model:open="planOpen" :title="planType" :width="800" :mask-closable="false">
    <a-form :model="planForm" ref="planFormRef">
      <a-form-item label="推送任务" name="taskName">
        <a-input v-model:value="planForm.taskName" :disabled="true" />
      </a-form-item>
      <a-form-item label="推送时间" name="planTime" :rules="[{ validator: planTimeCheck }]">
        <a-date-picker
          :showToday="false"
          v-model:value="planForm.planTime"
          format="YYYY-MM-DD"
          :allowClear="false"
          :disabled-date="(current) => !current || current < dayjs() || current >= dayjs(endTime)"
        />
      </a-form-item>
      <a-form-item
        v-if="planForm.taskName == '健康随访'"
        label="推送内容"
        name="itemName"
        :rules="[{ required: true }]"
      >
        <a-select
          v-model:value="planForm.itemName"
          showSearch
          :options="followTempList"
          @change="followTempChange"
        />
      </a-form-item>
      <a-form-item
        v-else
        label="推送内容"
        name="planContent"
        :rules="[{ required: true, validator: textTrimCheck }]"
      >
        <a-textarea
          v-model:value="planForm.planContent"
          :rows="15"
          :maxlength="5000"
          showCount
          style="width: 100%"
        />
      </a-form-item>
    </a-form>

    <template #footer>
      <div style="display: flex; justify-content: space-between">
        <a-button @click="planOpen = false">取消</a-button>
        <div v-if="planEditData">
          <a-button type="primary" danger @click="deletePlan">删除任务</a-button>
          <a-button type="primary" @click="savePlan">确认修改</a-button>
        </div>
      </div>
    </template>
  </a-modal>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, createVNode } from 'vue'
import {
  getManagePathExecution,
  getHistoryPath,
  getTemplateDetailList
} from '@/api/healthManaWorkbench'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
import { Empty, message, Modal } from 'ant-design-vue'
import Condition from '@/components/ConditionSearch/index.vue'
import store from '@/store'
import { Model } from 'echarts'
import { ExclamationCircleFilled } from '@ant-design/icons-vue'
import {
  planPushPlanHis,
  planPushPlanHisDelete,
  planPushPlanHisDetail
} from './planPushPlanHis.api'

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE

const emit = defineEmits(['goPage', 'refreshData'])

const open = ref(false)
const loading = ref(true)
const routePathIndex = ref(0)
const tempTabsIndex = ref(0)

// 修改执行方案
const planEditData = ref()
const planOpen = ref(false)
const planType = ref('')
const planFormRef = ref()
const planForm = reactive<any>({
  taskName: '',
  planTime: '',
  planContent: '',
  itemName: '',
  itemCode: ''
})

const condition = ref([
  {
    title: '',
    dataIndex: 'pushState',
    type: 'select',
    value: undefined,
    data: [
      {
        label: '未推送',
        value: false
      },
      {
        label: '已推送',
        value: true
      }
    ],
    placeholder: '推送状态'
  },
  {
    title: '',
    dataIndex: 'isRead',
    type: 'select',
    value: undefined,
    data: [
      {
        label: '未完成',
        value: false
      },
      {
        label: '已完成',
        value: true
      }
    ],
    placeholder: '患者执行情况'
  },
  {
    title: '',
    dataIndex: 'beginDate',
    type: 'dayRange',
    value: [],
    format: 'YYYY-MM-DD',
    placeholder: ['开始日期', '结束日期'],
    style: { width: '300px' }
  }
])

const detailInfoData = ref()

const manaageTypeDict = {
  饮食方案: '查看饮食详情',
  健康随访: '查看随访详情',
  健康监测: '查看监测数据'
}

const manaPlanTabData = reactive([
  {
    label: '健康处方',
    key: 'health'
  },
  {
    label: '饮食方案',
    key: 'diet'
  },
  {
    label: '运动方案',
    key: 'sports'
  },
  {
    label: '健康宣教',
    key: 'education'
  },
  {
    label: '健康随访',
    key: 'follow'
  },
  {
    label: '健康监测',
    key: 'monitor'
  },
  {
    label: '用药提醒',
    key: 'medication'
  },
  {
    label: '就诊提醒',
    key: 'remind'
  }
])

const planTimeCheck = async (_, value) => {
  return Promise.resolve()
}

const textTrimCheck = async (_, value) => {
  if (value.trim() === '') {
    return Promise.reject('推送内容不能为空')
  } else {
    return Promise.resolve()
  }
}

const templateTypeList = computed(() => {
  const data: any = []
  const permissionList: any = store.userApp.permissionList

  manaPlanTabData.forEach((item: any) => {
    if (permissionList.find((vo: any) => vo === `workbench:manaPlan:${item.key}`)) {
      data.push(item.label)
    }
  })
  return data
})

const pagination = ref<any>({
  current: 1,
  total: 0,
  pageSize: 10,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100'],
  showQuickJumper: true
})
const paginationChange = (page: any) => {
  pagination.value = { ...page }
  getDataList()
}

const columns = ref([
  {
    title: '推送时间',
    dataIndex: 'planTime',
    key: 'planTime',
    align: 'left',
    width: 150
  },
  {
    title: '推送内容',
    dataIndex: 'itemContent',
    key: 'itemContent',
    align: 'left'
  },
  {
    title: '推送状态',
    dataIndex: 'pushState',
    key: 'pushState',
    align: 'left',
    width: 120
  },
  {
    title: '患者执行情况',
    dataIndex: 'isRead',
    key: 'isRead',
    align: 'left',
    width: 120
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'left',
    width: 120
  }
])
const dataSource = ref([])

const routePath = ref([])

const managePlanId = ref('')

const startTime = ref('')
const endTime = ref('')

const hasEdit = ref(false)

const followTempList = ref()

const signData = ref<any>([
  {
    name: '身高',
    code: 'height'
  },
  {
    name: '体重',
    code: 'weight'
  },
  {
    name: 'BMI',
    code: 'bmi'
  },
  {
    name: '腰臀比',
    code: 'whr'
  },
  {
    name: '血压',
    code: 'bp'
  },
  {
    name: '心率',
    code: 'heartRate'
  },
  {
    name: '血糖',
    code: 'blood_sugar'
  },
  {
    name: '血氧',
    code: 'spo2'
  },
  {
    name: '血酮',
    code: 'blood_ketone'
  },
  {
    name: '尿酸',
    code: 'uric_acid'
  },
  {
    name: '睡眠',
    code: 'sleep'
  },
  {
    name: '饮水',
    code: 'water'
  },
  {
    name: '血脂',
    code: 'blood_fat'
  },
  {
    name: '肝功能',
    code: 'liver_function'
  }
])

const init = (data, isEdit) => {
  // const permissionList: any = store.userApp.permissionList
  // templateTypeList.value = []

  // manaPlanTabData.forEach((item: any) => {
  //   if (permissionList.find((vo: any) => vo === `workbench:manaPlan:${item.key}`)) {
  //     templateTypeList.value.push(item.label)
  //   }
  // })
  hasEdit.value = isEdit
  routePathIndex.value = 0
  pagination.value.current = 1
  loading.value = false
  open.value = true
  console.log(data)
  detailInfoData.value = JSON.parse(JSON.stringify(data))
  routePath.value = []
  managePlanId.value = ''
  const param = 'empi=' + data.empi + '&diseaseType=' + data.diseaseType
  getHistoryPath(param).then((res) => {
    if (res.data && res.data.length > 0) {
      routePath.value = res.data
      managePlanId.value = res.data[0].pathId
      startTime.value = res.data[0].startTime
      endTime.value = res.data[0].endTime
      getDataList()
    }
  })
}

const changeTab = (e) => {
  tempTabsIndex.value = e
  pagination.value.current = 1
  pagination.value.pageSize = 10
  dataSource.value = []

  condition.value.map((v) => {
    if (v.type === 'select') {
      v.value = undefined
    } else if (v.type === 'dayRange') {
      v.value = []
    } else {
      v.value = ''
    }
  })

  getDataList()
}

const initRouter = (data) => {
  switch (data.templateType) {
    case 'PRESCRIPTION':
      tempTabsIndex.value = templateTypeList.value.findIndex((item) => item === '健康处方')
      break
    case 'VISIT':
      tempTabsIndex.value = templateTypeList.value.findIndex((item) => item === '就诊提醒')
      break
    case 'FOLLOW_UP':
      tempTabsIndex.value = templateTypeList.value.findIndex((item) => item === '健康随访')
      break
    default:
      break
  }
  // console.log(tempTabsIndex.value)
  init(data, true)

  editPlan(data)
}

const getDataList = async () => {
  loading.value = true
  let param = {}
  const obj = condition.value.reduce((c, v) => {
    if (v.value || v.value === 0 || v.value === false) {
      if (v.dataIndex == 'beginDate') {
        return Object.assign(c, {
          beginTime: v.value.length ? dayjs(v.value[0]).format('YYYY-MM-DD 00:00:00') : '',
          time: v.value.length ? dayjs(v.value[1]).format('YYYY-MM-DD 23:59:59') : ''
        })
      } else {
        return Object.assign(c, { [v.dataIndex]: v.value })
      }
    } else {
      return c
    }
  }, {})
  param = {
    ...obj
  }

  getManagePathExecution({
    ...param,
    page: pagination.value.current,
    limit: pagination.value.pageSize,
    empi: detailInfoData.value.empi,
    userId: detailInfoData.value.userId,
    managePlanId: managePlanId.value,
    templateType: templateTypeList.value[tempTabsIndex.value],
    startTime: startTime.value,
    endTime: endTime.value,
    diseaseType: detailInfoData.value.diseaseType
  })
    .then((res) => {
      loading.value = false
      res.data.list.forEach((item) => {
        item.isSeeBtn = false
        item.seeUrl = {
          path: '/examinatePatients/index',
          query: {
            type: '',
            id: detailInfoData.value.userId,
            empi: detailInfoData.value.empi,
            back: window.location.hash == '#/healthManaWorkbench/dispatch/index' ? 3 : 4
          }
        }
        switch (item.templateType) {
          case '健康处方':
            if (!item.taskState) {
              item.isEdit = true
            }
            break
          case '健康宣教':
            item.itemContent = item.itemContent ? JSON.parse(item.itemContent).title : ''
            break
          case '健康随访':
            if (!item.taskState) {
              item.isEdit = true
            }
            item.isSeeBtn = true
            item.seeUrl.query.type = '5'
            item.seeUrl.query.taskId = item.taskId
            item.initContent = item.itemContent
            item.itemContent = item.itemName
            break
          case '健康监测':
            item.isSeeBtn = true
            item.seeUrl.query.type = '2'
            item.seeUrl.query.labelName = signData.value.find(
              (vo: any) => vo.name == JSON.parse(item.itemContent).sings
            ).code
            item.itemContent = item.itemName
            break
          case '用药提醒':
            break
          case '就诊提醒':
            if (!item.taskState) {
              item.isEdit = true
            }
            break
          case '饮食方案':
            item.isSeeBtn = true
            item.seeUrl.query.type = '7'
            item.seeUrl.query.dietDate = dayjs(item.planTime).format('YYYY-MM-DD')
            break
          default:
            break
        }
      })

      dataSource.value = res.data.list
      pagination.value.total = res.data.total
    })
    .catch(() => {
      loading.value = false
    })
}

const searchHandle = () => {
  pagination.value.current = 1
  getDataList()
}

const reset = () => {
  pagination.value.current = 1
  pagination.value.pageSize = 10
  condition.value.map((v) => {
    if (v.type === 'select') {
      v.value = undefined
    } else if (v.type === 'dayRange') {
      v.value = []
    } else {
      v.value = ''
    }
  })
  getDataList()
}

// 跳转
const goDetail = (data) => {
  open.value = false
  emit('goPage', data.seeUrl.query)
}

const routePathHandle = (data, index) => {
  routePathIndex.value = index
  managePlanId.value = data.pathId
  startTime.value = data.startTime
  endTime.value = data.endTime
  tempTabsIndex.value = 0

  dataSource.value = []
  pagination.value.current = 1
  pagination.value.pageSize = 10
  getDataList()
}

// 修改事件
const editPlan = async (data: any) => {
  console.log(data)
  planOpen.value = true
  if (data.templateType === '健康随访') {
    const res = await getTemplateDetailList({
      templateType: null,
      templateAffiliation: null,
      platformId: store.userStore.platformId
    })

    res.data.map((item: any) => {
      item.label = item.templateName
      item.value = item.templateName
    })

    followTempList.value = res.data.filter((item) => {
      return item.templateType === '健康随访'
    })
  }

  planPushPlanHisDetail({ empi: data.empi, detailId: data.detailId }).then((res) => {
    planEditData.value = res.data

    nextTick(() => {
      planForm.planTime = dayjs(dayjs(planEditData.value.planTime).format('YYYY-MM-DD'))
      let planTaskNameContent: any = ''
      if (followTempList.value && followTempList.value.length) {
        planTaskNameContent = followTempList.value.find(
          (tem) => tem.templateName == planEditData.value.itemName
        )
      }
      planForm.planContent =
        data.templateType == '健康随访'
          ? planTaskNameContent
            ? planTaskNameContent.content
            : ''
          : planEditData.value.itemContent
      planForm.itemName = planEditData.value.itemName
      planForm.taskName = planEditData.value.templateType
      planType.value = '修改' + planForm.taskName
    })
  })
}

// 选择随访模板
const followTempChange = (e) => {
  console.log(e)
  const selectedTemplate = followTempList.value.find((tem) => tem.templateName == e)
  planForm.planContent = selectedTemplate ? selectedTemplate.content : ''
  planForm.itemCode = selectedTemplate ? selectedTemplate.id : ''
}

const savePlan = () => {
  planFormRef.value
    .validate()
    .then(() => {
      const param = {
        empi: planEditData.value.empi,
        diseaseType: planEditData.value.diseaseType,
        detailId: planEditData.value.detailId,
        planTime:
          dayjs(planForm.planTime).format('YYYY-MM-DD') +
          dayjs(planEditData.value.planTime).format(' HH:mm:ss'),
        itemContent: planForm.planContent,
        itemName: planForm.itemName,
        taskId: planEditData.value.taskId,
        itemCode: planForm.itemCode,
        templateType: planForm.taskName
      }
      console.log(param)
      planPushPlanHis(param).then((res) => {
        message.success('修改成功')

        open.value = false
        planOpen.value = false
        setTimeout(() => {
          emit('refreshData')
        }, 200)
      })
    })
    .catch(() => {})
}

const deletePlan = () => {
  Modal.confirm({
    title: '删除',
    icon: createVNode(ExclamationCircleFilled, {
      style: {
        color: 'var(--color--danger)'
      }
    }),
    content: '确认是否删除任务',
    okText: '确定',
    okButtonProps: {
      danger: true,
      type: 'primary'
    },
    cancelText: '取消',
    onOk() {
      planPushPlanHisDelete({
        taskId: planEditData.value.taskId,
        detailId: planEditData.value.detailId,
        empi: planEditData.value.empi
      }).then((res) => {
        message.success('删除成功')
        console.log('OK')
        open.value = false
        planOpen.value = false
        setTimeout(() => {
          emit('refreshData')
        }, 200)
      })
    },
    onCancel() {
      console.log('Cancel')
    }
  })
}

defineExpose({
  init,
  initRouter
})
</script>
<style lang="less" scoped>
.route-item {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 97px;
  padding: 12px;
  cursor: pointer;
  background: #f2f3f5;
  border: 1px solid #e5e6eb;
  border-radius: 4px;

  .route-name {
    width: 132px;
    font-size: 14px;
    font-weight: bold;
    color: #1d2129;
  }

  .route-time {
    color: #1d2129;
  }

  .mana-span {
    color: #165dff;
    background-color: #fff;
  }

  .over-span {
    color: #ff7d00;
    background-color: #fff;
  }

  .close-span {
    color: #86909c;
    background-color: #fff;
  }
}

.route-manage-name {
  color: #fff;
}

.route-manage-time {
  color: #fff;
}

.route-item-active {
  background-color: #165dff;

  .route-name {
    color: #fff;
  }

  .route-time {
    color: #fff;
  }

  .mana-span {
    background-color: #e8f3ff;
  }

  .over-span {
    background-color: #e8f3ff;
  }

  .close-span {
    background-color: #e8f3ff;
  }
}

.route-path-state {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 52px;
  height: 20px;
  font-size: 12px;
  border-radius: 2px;
}
</style>
